package com.stylefeng.guns.modular.system.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.common.constant.state.SpType;
import com.stylefeng.guns.core.model.SysFunTree;
import com.stylefeng.guns.core.util.JwtTokenUtil;
import com.stylefeng.guns.modular.system.dao.OrgcategoryRoleFunctionMapper;
import com.stylefeng.guns.modular.system.model.OrgcategoryFunction;
import com.stylefeng.guns.modular.system.model.OrgcategoryRole;
import com.stylefeng.guns.modular.system.model.OrgcategoryRoleFunction;
import com.stylefeng.guns.modular.system.model.SysPrivilege;
import com.stylefeng.guns.modular.system.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2018-09-17
 */
@Service
public class OrgcategoryRoleFunctionServiceImpl extends ServiceImpl<OrgcategoryRoleFunctionMapper, OrgcategoryRoleFunction> implements IOrgcategoryRoleFunctionService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IOrgcategoryRoleService orgcategoryRoleService;
    @Autowired
    private IOrgcategoryFunctionService orgcategoryFunctionService;
    @Autowired
    private IRoleCwService roleCwService;
    @Autowired
    private ISysPrivilegeService privilegeService;

    //@Resource
    //private OrgcategoryRoleFunctionMapper orgcategoryRoleFunctionMapper;

    /** ****************************************sasazaixian@2018-10-04 start**************************************** **/
    /**
     * 查询机构分类角色功能
     * @param sorId 机构分类角色ID

     * @return
     * @throws Exception
     */
    public List<SysFunTree> selectListOrgcategoryRoleFunction(String  sorId) throws DataAccessException{

        List<SysFunTree> listSysFun = new ArrayList<SysFunTree>();
        // 获取机构分类ID
        OrgcategoryRole orgcategoryRole=orgcategoryRoleService.findById(sorId);
        String orgcategoryid = orgcategoryRole.getSocId();

        // 获取当前角色所有功能
        OrgcategoryRoleFunction orgcategoryRoleFun=new OrgcategoryRoleFunction();
        orgcategoryRoleFun.setSorId(sorId);
        //List<OrgcategoryRoleFunction> listSysCategoryRoleFun = orgcategoryRoleFunctionMapper.selectListOrgcategoryRoleFunction(orgcategoryRoleFun);

        SysPrivilege selPrivilege=new SysPrivilege();
        selPrivilege.setSpType(SpType.ORGCATEROLE.getCode());
        selPrivilege.setSpTypeId(sorId);
        List<SysPrivilege> listSysCategoryRoleFun = privilegeService.selectListSysPrivilege(selPrivilege);

        // 根据机构分类，获取机构功能树
        List<OrgcategoryFunction> listSysCategoryFun = orgcategoryFunctionService.selectListOrgcategoryFunction(orgcategoryid);
        if (listSysCategoryFun != null) {
            for (OrgcategoryFunction tempOrgCateFun:listSysCategoryFun) {
                SysFunTree sysFunTree = new SysFunTree();
                sysFunTree.setChecked("false");
                for(SysPrivilege sysPrivilege:listSysCategoryRoleFun){
                    if(sysPrivilege.getSpFunctionId().intValue()==tempOrgCateFun.getSpFunctionId().intValue()
                            || sysPrivilege.getSpMethod().indexOf("["+tempOrgCateFun.getSpFunctionId().toString()+"]")>-1){
                        sysFunTree.setChecked("true");
                        break;
                    }
                }
                sysFunTree.setId(""+tempOrgCateFun.getSpFunctionId());
                sysFunTree.setPid(tempOrgCateFun.getSpFunctionPid());
                sysFunTree.setName(tempOrgCateFun.getSpFunctionName());
                if(tempOrgCateFun.getSfIsmenu().equals("1")){
                    sysFunTree.setFunType("F");//tree节点表示功能
                }else{
                    sysFunTree.setFunType("M");//tree节点表示功能
                }
                listSysFun.add(sysFunTree);
            }
        }
        listSysCategoryRoleFun.clear();
        listSysCategoryFun.clear();
        return listSysFun;
    }
    /**
     * 保存机构分类角色功能
     * @param orgcategoryRoleFunction 机构分类角色功能对象
     * @param  token 令牌
     * @return
     * @throws Exception
     */
    @Transactional
    public int insertOrgcategoryRoleFunction(OrgcategoryRoleFunction orgcategoryRoleFunction,String token)throws DataAccessException {
    if (orgcategoryRoleFunction == null || StringUtils.isBlank(orgcategoryRoleFunction.getSorId())) {
            throw new RuntimeException("机构分类角色不能为空！");
        }

        Date currentTime=DateTime.now();
        String subject = JwtTokenUtil.getClaimFromToken(token).getSubject();//用户ID
        //删除当前机构分类角色原有功能
        OrgcategoryRoleFunction delRoleFunction=new OrgcategoryRoleFunction();
        delRoleFunction.setSorId(orgcategoryRoleFunction.getSorId());
        this.deleteOrgcategoryRoleFunction(delRoleFunction);

        //新增当前机构分类角色新配置功能
        // [{fid:功能id,sm:[操作id]-[操作id],srid:机构分类角色id}]
        String savaTxt=orgcategoryRoleFunction.getObjArrys();
        //保存机构分类所拥有的功能和操作
        JSONArray arryOBj=JSONArray.parseArray(savaTxt);
        for(int i=0;i<arryOBj.size();i++){
            JSONObject obj=arryOBj.getJSONObject(i);

            SysPrivilege privilege=new SysPrivilege();
            privilege.setSpType(SpType.ORGCATEROLE.getCode());
            privilege.setSpTypeId(obj.getString("sorid"));
            privilege.setSpFunctionId(Integer.parseInt(obj.getString("fid")));
            privilege.setSpMethod(obj.getString("sm"));
            privilegeService.insertSysPrivilege(privilege);
           /* OrgcategoryRoleFunction tempOrgcategoryRoleFunction = new OrgcategoryRoleFunction();
            //机构分类角色
            tempOrgcategoryRoleFunction.setSorId(Integer.parseInt(obj.getString("sorid")));
            //功能id
            tempOrgcategoryRoleFunction.setSpFunctionId(Integer.parseInt(obj.getString("fid")));
            //功能对应的操作
            tempOrgcategoryRoleFunction.setSpMethod(obj.getString("sm"));
            tempOrgcategoryRoleFunction.setCreateTime(currentTime);

            tempOrgcategoryRoleFunction.setCreateUser(subject);

            orgcategoryRoleFunctionMapper.insertOrgcategoryRoleFunction(tempOrgcategoryRoleFunction);*/
        }
        //同步组织角色和功能
        //orgcategoryRoleService.addRoletoSubOrg(orgcategoryRoleFunction.getSorId().toString(),token);

        /*RoleCw selSysRole = new RoleCw();
        selSysRole.setSrcTemId(orgcategoryRoleFunction.getSorId());
        selSysRole.setSrSource("1");
        List<RoleCw> listSysRole = roleCwService.selectListRoleCw(selSysRole);

        for (RoleCw temSysRole : listSysRole) {
            SysPrivilege tempSysPrivilege = new SysPrivilege();
            tempSysPrivilege.setSpTypeId(temSysRole.getSrId());
            tempSysPrivilege.setSpType(SpType.ROLE.getCode());
            privilegeService.deleteSysPrivilege(tempSysPrivilege);
            for (int i = 0; i <arryOBj.size(); i++) {
                JSONObject obj = arryOBj.getJSONObject(i);
                tempSysPrivilege = new SysPrivilege();
                tempSysPrivilege.setSpType(SpType.ROLE.getCode());
                tempSysPrivilege.setSpTypeId(temSysRole.getSrId());
                tempSysPrivilege.setSpFunctionId(Integer.parseInt(obj.getString("fid")));
                tempSysPrivilege.setSpMethod(obj.getString("sm"));
                tempSysPrivilege.setSoId(temSysRole.getSoId());
                privilegeService.insertSysPrivilege(tempSysPrivilege);
            }
        }*/
        return 0;
    }
    /**
     * 删除机构分类角色功能
     * @param orgcategoryRoleFunction 机构分类角色功能对象

     * @return
     * @throws Exception
     */
    public int deleteOrgcategoryRoleFunction(OrgcategoryRoleFunction orgcategoryRoleFunction)throws DataAccessException{
        if(orgcategoryRoleFunction==null || orgcategoryRoleFunction.getSorId()==null || orgcategoryRoleFunction.getSorId().toString().trim().length()<1){
            throw new RuntimeException("机构分类角色不能为空！");
        }
        SysPrivilege privilege=new SysPrivilege();
        privilege.setSpType(SpType.ORGCATEROLE.getCode());
        privilege.setSpTypeId(orgcategoryRoleFunction.getSorId());
        return privilegeService.deleteSysPrivilege(privilege);
        //return orgcategoryRoleFunctionMapper.deleteOrgcategoryRoleFunction(orgcategoryRoleFunction);
    }
}
